package com.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.demo.common.dto.StockReturnDto;
import com.demo.common.model.Stock;
import com.demo.common.model.Stockinfo;

public class HttpUtil {

	public static Document getDocumentByGet(String url) throws Exception {
		return Jsoup.connect(url).get();
	}
	
	public static boolean getStockInfoList(String[] stockCodes, List<Stockinfo> stockInfoList) {
		StringBuffer codeBuf = new StringBuffer();
		for (int i = 0; i < stockCodes.length; i++) {
			codeBuf.append(stockCodes[i])
				   .append(",");
		}
		String httpArg = "stockid=" + codeBuf.substring(0, codeBuf.length()-2) + "&list=1";
		String resultStr = request("http://apis.baidu.com/apistore/stockservice/stock", httpArg);
		StockReturnDto retData = JSON.parseObject(resultStr, StockReturnDto.class);
		if(0 == retData.getErrNum()) {
			com.demo.common.dto.Stockinfo[] dto = retData.getRetData().getStockinfo();
			for (com.demo.common.dto.Stockinfo stockinfo : dto) {
				Stockinfo tmp = new Stockinfo();
				
				BigDecimal openningPrice = stockinfo.getOpenningPrice();
				BigDecimal currentPrice = stockinfo.getCurrentPrice();
				BigDecimal hPrice = stockinfo.gethPrice();
				BigDecimal lPrice = stockinfo.getlPrice();
				if(openningPrice.compareTo(new BigDecimal(0)) > 0 &&
						currentPrice.compareTo(new BigDecimal(0)) > 0 &&
						hPrice.compareTo(new BigDecimal(0)) > 0 &&
						lPrice.compareTo(new BigDecimal(0)) > 0) {
					tmp.setStockCode(stockinfo.getCode());
					tmp.setDate(stockinfo.getDate());//数据时间
					tmp.setTime(stockinfo.getTime());//具体时间
					tmp.setOpenningPrice(openningPrice);//开盘价
					tmp.setCurrentPrice(currentPrice);
					tmp.setHPrice(hPrice);//今日最高价
					tmp.setLPrice(lPrice);//今日最低价
					stockInfoList.add(tmp);
					
					//判断是否有交易信号
					//1.计算下影线的长度
					BigDecimal st = openningPrice.subtract(currentPrice).abs();
					BigDecimal xyx = new BigDecimal(0);
					BigDecimal syx = new BigDecimal(0);
					if(openningPrice.compareTo(currentPrice) == 1) {//如果开盘价高于收盘价
						xyx = currentPrice.subtract(lPrice);
						syx = hPrice.subtract(openningPrice);
					} else {
						xyx = openningPrice.subtract(lPrice);
						syx = hPrice.subtract(currentPrice);
					}
					if(st.compareTo(new BigDecimal(0)) > 0) {
						if(xyx.divide(st, 2).compareTo(new BigDecimal(5)) >= 0) {//有买入信号
							Stock stock = Stock.dao.findByCode(stockinfo.getCode());
							stock.setBuySignals(1);
							stock.setSignalsTime(new Date());
							stock.setDailyChar(stockinfo.getDayurl());
							stock.setWeight(xyx.divide(st, 2));
							stock.update();
							
						} else if (syx.divide(st, 2).compareTo(new BigDecimal(5)) >= 0) {//有卖出信号
							Stock stock = Stock.dao.findByCode(stockinfo.getCode());
							stock.setSellSignals(1);
							stock.setSignalsTime(new Date());
							stock.setDailyChar(stockinfo.getDayurl());
							stock.setWeight(xyx.divide(st, 2));
							stock.update();
						}
					}
				}
			}
		} else {
			
		}
		return true;
	}
	
	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  "720589e49d98af788ece529de8e8ab36");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	public static void main(String[] args) {
		//String jsonStr = request("http://apis.baidu.com/apistore/stockservice/stock", "stockid=sh900933,sh201010&list=1");
		//StockReturnDto retData = JSON.parseObject(jsonStr, StockReturnDto.class);
		//System.out.println(request("http://apis.baidu.com/apistore/stockservice/stock", "stockid=sh900933,sh201010&list=1"));
		System.out.println(Integer.parseInt("sz002230".substring(2, "sz002230".length() - 1)));
	}

}
